<?php

namespace slinks\extensions\twig\compiler;

use slinks\core\DependencyInjection\Reference;
use slinks\core\DependencyInjection\Definition;
use slinks\core\dependencyInjectionExt\compiler\AbstractInterfaceProcessingPass;
use slinks\extensions\twig\TwigExtension;
use slinks\core\DependencyInjection\ContainerBuilder;
use slinks\core\DependencyInjection\Compiler\CompilerPassInterface;

class TwigExtensionPass extends AbstractInterfaceProcessingPass {

    private $twigEnvironmentDef = null;

    function __construct() {
        parent::__construct('\\Twig_Extension');
    }

    /**
     * Allows sublcasses to check any pre-requisites prior to processing individual definitions. 
     * 
     * @param ContainerBuilder $container
     * @return Boolean true if the definition processing should occur. 
     */
    public function shouldProcessBegin(ContainerBuilder $container) {
        // we must make sure the twig extension is configured and the twig classes are available.
        $ret = $container->hasDefinition(TwigExtension::TWIG_ENGINE) && class_exists('\\Twig_Extension');

        if ($ret) {
            $this->twigEnvironmentDef = $container->getDefinition(TwigExtension::TWIG_ENGINE);
            
            // add symfony created extensions
            $this->twigEnvironmentDef->addMethodCall('addExtension',array(new Definition('Twig_Extensions_Extension_Debug')));
            $this->twigEnvironmentDef->addMethodCall('addExtension',array(new Definition('Twig_Extensions_Extension_Text')));
            $this->twigEnvironmentDef->addMethodCall('addExtension',array(new Definition('Twig_Extensions_Extension_I18n')));
        }
        return $ret;
    }

    /**
     * You can modify the Definition here before it is dumped to PHP code.
     * 
     * @param string $id the service definition id; 
     * @param Definition $definition
     */
    public function processDefinition($id, Definition $definition) {

        $this->twigEnvironmentDef->addMethodCall('addExtension', array(new Reference($id)));
    }

}